package com.itgm.jiayun_web_project.interceptor;

import com.itgm.jiayun_web_project.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("token interceptor preHandle 拦截器");
        //获取请求路径
        String url = request.getRequestURI();
        //判断路径是否为登录，如果是登录，则不拦截
        if(url.contains("/login")){
            return true;
        }
        //判断请求头中是否有token，如果没有，则拦截
        String token = request.getHeader("token");
        if(token == null || token.isEmpty()){
            response.sendError(401,"token is null");
            return false;
        }
        //jwt验证token
        try {
            Claims claims = JwtUtils.parseToken(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("token interceptor preHandle 验证通过");
        return true;
    }
}
